<template>
  <div class="page-container">
    <div class="container">
      <el-container style="height: 100%;">
        <el-header style="margin: 0;height: 40px">
          <el-button type="primary" @click="sendClockInRequest">发送上班打卡</el-button>
          <el-button type="primary" @click="sendClockOutRequest">发送下班打卡</el-button>
        </el-header>
        <el-main style="margin-top: 0">
          <el-table :data="sortedAttendanceRecords" style="width: 100%" v-loading="loading">
            <el-table-column prop="clockTime" label="打卡发起时间(由近到远)"></el-table-column>
            <el-table-column prop="clockInType" label="打卡类型"></el-table-column>
            <el-table-column prop="clockedInCount" label="已打卡人数" width="100"></el-table-column>
            <el-table-column prop="absentCount" label="缺勤人数" width="100"></el-table-column>
            <el-table-column prop="leaveCount" label="请假人数" width="100"></el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="text" @click="showEmployeeDetails(scope.row)">查看缺勤/未打卡员工</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              background
              layout="prev, pager, next"
              prev-text="←旧👈"
              next-text="👉新→"
              :total="pagination2.total"
              :page-size="pagination2.size"
              v-model:current-page="pagination2.page"
              @current-change="fetchAttendanceRecords"
              style="margin-top: 20px; text-align: center;"
          />
        </el-main>
        <el-dialog title="缺勤/请假员工信息" v-model="dialogVisible" width="50%">
          <el-table :data="selectedEmployees" style="width: 100%">
            <el-table-column prop="id" label="员工ID"></el-table-column>
            <el-table-column prop="fullName" label="姓名"></el-table-column>
            <el-table-column prop="attendanceStatus" label="状态"></el-table-column>
          </el-table>
          <el-pagination
              background
              layout="prev, pager, next"
              :total="pagination.total"
              :page-size="pagination.size"
              v-model:current-page="pagination.page"
              @current-change="showEmployeeDetails"
              style="margin-top: 20px; text-align: center;"
          />
        </el-dialog>
      </el-container>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const attendanceRecords = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const selectedEmployees = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  total: 0,
});
const pagination2 = ref({
  page: 1,
  size: 8,
  total: 0,
  pages: 1,
});
const lastSendTime = ref(null);
const FIVE_MINUTES = 5 * 60 * 1000; // 五分钟的毫秒数

const sortedAttendanceRecords = computed(() => {
  return [...attendanceRecords.value].sort((a, b) => new Date(b.clockTime) - new Date(a.clockTime));
});

const sendClockInRequest = async () => {
  const now = new Date().getTime();
  if (now - lastSendTime.value < FIVE_MINUTES) {
    ElMessage.warning('五分钟内无法重复发送上班/下班打卡请求！');
    return;
  }
  try {
    const response = await axios.post('http://localhost:8080/admin/clockInRequest');
    ElMessage.success(response.data.message || '发送上班打卡请求成功');
    lastSendTime.value = now;
    await fetchAttendanceRecords();
  } catch (error) {
    console.error('Network error:', error); // 添加错误日志
    ElMessage.error('网络错误，请重试');
  }
};

const sendClockOutRequest = async () => {
  const now = new Date().getTime();
  if (now - lastSendTime.value < FIVE_MINUTES) {
    ElMessage.warning('五分钟内无法重复发送上班/下班打卡请求！');
    return;
  }
  try {
    const response = await axios.post('http://localhost:8080/admin/clockOutRequest');
    ElMessage.success(response.data.message || '发送下班打卡请求成功');
    lastSendTime.value = now;
    await fetchAttendanceRecords();
  } catch (error) {
    console.error('Network error:', error); // 添加错误日志
    ElMessage.error('网络错误，请重试');
  }
};

const fetchAttendanceRecords = async () => {
  try {
    loading.value = true;
    const response = await axios.get('http://localhost:8080/admin/attendanceCountRecords', {
      params: {
        page: pagination2.value.page,
        size: pagination2.value.size,
      },
    });
    if (response.data) {
      attendanceRecords.value = response.data.data.records;
      pagination2.value.total = response.data.data.total;
      pagination2.value.pages = Math.ceil(response.data.data.total / pagination2.value.size);
    } else {
      ElMessage.error('获取打卡记录失败');
    }
  } catch (error) {
    console.error('Fetch attendance records error:', error); // 添加错误日志
    ElMessage.error('网络错误，请重试');
  } finally {
    loading.value = false;
  }
};

const showEmployeeDetails = async (record) => {
  try {
    const response = await axios.get(`http://localhost:8080/admin/attendance/employees`, {
      params: {
        page: pagination.value.page,
        size: pagination.value.size,
        clockTime: record.clockTime,
      },
    });
    if (response.data) {
      selectedEmployees.value = response.data.data.records;
      pagination.value.total = response.data.data.total;
      dialogVisible.value = true;
    } else {
      ElMessage.error('获取员工信息失败');
    }
  } catch (error) {
    console.error('Show employee details error:', error); // 添加错误日志
    ElMessage.error('网络错误，请重试');
  }
};

const initialLoad = async () => {
  try {
    const response = await axios.get('http://localhost:8080/admin/attendanceCountRecords', {
      params: {
        page: 1,
        size: pagination2.value.size,
      },
    });
    if (response.data) {
      pagination2.value.total = response.data.data.total;
      pagination2.value.pages = Math.ceil(response.data.data.total / pagination2.value.size);
      pagination2.value.page = pagination2.value.pages; // 设置为最后一页
      await fetchAttendanceRecords(); // 再次调用以加载最后一页的数据
    } else {
      ElMessage.error('获取打卡记录失败');
    }
  } catch (error) {
    console.error('Initial load error:', error); // 添加错误日志
    ElMessage.error('网络错误，请重试');
  }
};

onMounted(() => {
  initialLoad();
});
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>
